import 'package:flutter/material.dart';

class StateManagerDemo extends StatefulWidget {
  @override
  _StateManagerDemoState createState() {
    return _StateManagerDemoState();
  }
}

class _StateManagerDemoState extends State<StateManagerDemo> {
  var _count = 0;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return CounterProvider(
      count: _count,
      increaseCount: () {
        addCount();
      },
      child: Stack(
        children: [
          // Counter(_count),
          Counter(),
          Align(
            alignment: Alignment(1, 1),
            child: FloatingActionButton(
              onPressed: addCount,
              child: Icon(Icons.add),
            ),
          ),
        ],
      ),
    );
  }

  void addCount() {
    setState(() {
      _count++;
    });
  }
}

class Counter extends StatelessWidget {
  /*  int _count;

  Counter(this._count);*/

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      // 父-> 子 组件 通过构造函数传递参数 (缺点 当多级层级嵌套的时候，会来回传递)
      child: ElevatedButton(
        onPressed: () {
          CounterProvider.of(context).increaseCount();
        },
        child: Text('${CounterProvider.of(context).count}'),
      ),
    );
  }
}

class CounterProvider extends InheritedWidget {
  final int count;
  final VoidCallback increaseCount;

  CounterProvider({
    required this.count,
    required this.increaseCount,
    required super.child,
  });

  @override
  bool updateShouldNotify(covariant CounterProvider oldWidget) {
    return true;
  }

  static CounterProvider of(BuildContext context) {
    final provider = context
        .dependOnInheritedWidgetOfExactType<CounterProvider>();
    if (provider == null) {
      throw FlutterError('CounterProvider not found in context');
    }
    return provider;
  }
}
